package com.snail.auth.action;

import com.common.ResultUtil;
import com.common.entity.BaseController;
import com.common.util.StringUtil;
import com.snail.auth.entity.AuthMenu;
import com.snail.auth.service.AuthMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Api(tags = {"manage auth 0 menu"}, value = "系统菜单")
@RestController
@RequestMapping("auth/menu")
public class AuthMenuController extends BaseController {
    @Autowired
    private AuthMenuService menuService;

    @GetMapping
    public Map<String, Object> list() throws Exception {
        List<AuthMenu> menus = menuService.list();
        return ResultUtil.result(menus);
    }

    @ApiOperation(value = "查询指定菜单详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "菜单ID", required = true, dataType = "long", paramType = "path"),
    })
    @GetMapping(value = "/{id}")
    public Map<String, Object> detail(@PathVariable Long id) {
        AuthMenu menu = menuService.getByKey(id);
        if (menu.getParentId() != 0L) {
            AuthMenu parentMenu = menuService.getByKey(menu.getParentId());
            menu.setParentName(parentMenu.getName());
        } else {
            menu.setParentName("--顶级菜单--");
        }
        return ResultUtil.result(menu);
    }


    @ApiOperation(value = "保存")
    @PostMapping
    public Map<String, Object> save(AuthMenu menu) throws Exception {
        if (StringUtil.isEmpty(menu.getId())) {
            menu.setId(menuService.newId(menu.getParentId()));
        }
        menuService.save(menu);
        return ResultUtil.result(menu);
    }

    @DeleteMapping(value = "/{id}")
    public Map<String, Object> del(@PathVariable Long id) throws Exception {
        menuService.del(id);
        return ResultUtil.result();
    }

    @ApiOperation(value = "菜单结构树")
    @GetMapping("/tree")
    public Map<String, Object> tree() {
        return ResultUtil.result(menuService.treeData());
    }

}
